package com.framework.middleware.zookeeper;

import com.alibaba.fastjson.JSON;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;

/**
 * @author chaolong.jin
 * @description
 * @date 2019/08/09 14:58
 */
public class ZkClient {

    public  ZooKeeper getZookeeper(String connectionString, int sessionTimeout, Watcher watcher) {
        ZooKeeper zooKeeper = null;
        try {
            zooKeeper = new ZooKeeper(connectionString, sessionTimeout, watcher);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return zooKeeper;
    }

    public  Watcher getConnectionWatcher() {
        return new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                if (event.getState().equals(Event.KeeperState.SyncConnected)) {
                    System.out.println("链接成功" + "path=  " + event.getPath());
                } else {
                    System.out.println("Connection error" + JSON.toJSONString(event));
                }
            }
        };
    }

}
